package com.ruoyi.web.controller.front;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.http.IAMHttpUtils;
import com.ruoyi.common.utils.http.HttpClientUtils;
import com.ruoyi.framework.jwt.config.properties.JwtProjectProperties;
import com.ruoyi.framework.jwt.utlis.JwtUtil;
import com.ruoyi.system.domain.OaOrg;
import com.ruoyi.system.domain.OaOrgUser;
import com.ruoyi.system.domain.Org;
import com.ruoyi.system.domain.OrgUser;
import com.ruoyi.system.service.IOaOrgService;
import com.ruoyi.system.service.IOaOrgUserService;
import com.ruoyi.system.service.IOrgService;
import com.ruoyi.system.service.IOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.ruoyi.common.core.domain.Ztree;

import javax.servlet.http.HttpServletRequest;

import static com.ruoyi.common.utils.http.IAMHttpUtils.TYPE_JSON;

@Controller
@RequestMapping("/front")
public class FrontController extends BaseController {

    @Autowired
    private JwtProjectProperties properties;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOrgUserService orgUserService;

    @Autowired
    private IOaOrgService oaOrgService;

    @Autowired
    private IOaOrgUserService oaOrgUserService;


    public static final String cnodcCode = "zdgateway";
    public static final String cnodcSecret = "yw8femzh3gndo0lccf364ggd3kafgqqq";
    public static final String cnodcTenanCode = "cnodc";

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password) {

        // 初始化数据字典Map
        username = username.toLowerCase();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return AjaxResult.error("请输入用户名或密码");
        }
        JSONObject resultJson = new JSONObject();
        try {
            final Base64.Encoder encoder = Base64.getEncoder();
            JSONObject json = new JSONObject();
            json.put("appCode", encoder.encodeToString(cnodcCode.getBytes("UTF-8")));
            json.put("secret", encoder.encodeToString(cnodcSecret.getBytes("UTF-8")));
            json.put("tenantCode", encoder.encodeToString(cnodcTenanCode.getBytes("UTF-8")));
            json.put("username", encoder.encodeToString(username.getBytes("UTF-8")));
            json.put("pwd", encoder.encodeToString(password.getBytes("UTF-8")));
            System.out.println("params:" + json.toString());
            String result = IAMHttpUtils.doPost("http://rfiam.cnpc/ngiam-rst/oauth2/getToken", json.toString(), TYPE_JSON);
            System.out.println("result:" + result);
            JSONObject resultMap = JSON.unmarshal(result, JSONObject.class);
            resultJson.put("code", "fail");
            if (null != resultMap && resultMap.get("code").equals("SUCCESS")) {
                Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
                JSONObject json1 = new JSONObject();
                String token = (String) data.get("accessToken");
                json1.put("token", token); // expire:360000
                String result1 = IAMHttpUtils.doPost("http://rfiam.cnpc/ngiam-rst/oauth2/getUserInfo", json1.toString(), TYPE_JSON);
                System.out.println("result1:" + result1);
                Map<String, Object> resultMap1 = JSON.unmarshal(result1, JSONObject.class);
                if (null != resultMap1 && resultMap1.get("code").equals("SUCCESS")) {
                    JSONObject.JSONArray jsonArray = (JSONObject.JSONArray) resultMap1.get("data");
                    if (null != jsonArray && jsonArray.size() > 0) {
                        Map<String, Object> usermap = (Map<String, Object>) jsonArray.get(0);
                        Map<String, Object> usermap1 = (Map<String, Object>) usermap.get("mappingAttrs");
                        if (null != usermap1) {
                            System.out.println("usermap1:" + usermap1);
                            String displayName = String.valueOf(usermap1.get("displayName"));//2020-01-21
                            System.out.println("aaa:" + displayName);
                            resultJson.put("displayname", usermap1.get("displayName"));
                            resultJson.put("mobile", usermap1.get("mobile"));
                            resultJson.put("email", usermap1.get("email"));
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
                            String today = sf.format(new Date());
                            resultJson.put("today", today);

                            String resultToken = JwtUtil.getToken(displayName, properties.getSecret(), properties.getExpired());
                            resultJson.put("token", resultToken);
                        }
                    }

                    resultJson.put("code", "success");
                }

            } else {
                resultJson.put("code", "fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.put("code", "fail");
        }

        return AjaxResult.success(resultJson);
    }

    /**
     * 查询组织机构列表
     */
    @GetMapping("/org/treeData")
    @CrossOrigin
    @ResponseBody
    public List<Ztree> treeData() {
        Org org = new Org();
        List<Ztree> list = orgService.selectOrgTree(org);
        return list;
    }
    /**
     * 查询组织机构列表
     */
    @PostMapping("/org/list")
    @CrossOrigin
    @ResponseBody
    public AjaxResult orgList() {
        Org org = new Org();
        List<Org> list = orgService.selectOrgList(org);
        return AjaxResult.success(list);
    }
    /**
     * 分页查询组织机构列表
     */
    @PostMapping("/org/pageList")
    @CrossOrigin
    @ResponseBody
    public AjaxResult orgPageList() {
        Org org = new Org();
        startPage();
        List<Org> list = orgService.selectOrgList(org);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 查询所有组织人员列表
     */
    @PostMapping("/orgUser/list")
    @CrossOrigin
    @ResponseBody
    public TableDataInfo orgUserList(HttpServletRequest request,Long orgId) {
        Org org = orgService.selectOrgById(orgId);
        List<Org> list = orgService.selectOrgListByParentCode(org.getCode());
        if (list.size()==0){
            list.add(org);
        }
        String [] groups = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Org tempOrg = list.get(i);
            groups[i]=tempOrg.getCode();
        }
        startPage();
        List<OrgUser> resultList = orgUserService.selectOrgUserListByCode(groups);
        return getDataTable(resultList);
    }

    /**
     * 通过组织机构查询所有组织人员列表
     */
    @PostMapping("/orgUser/listByOrg")
    @CrossOrigin
    @ResponseBody
    public AjaxResult listByOrg() {
        OrgUser orgUser = new OrgUser();
        List<OrgUser> list = orgUserService.selectOrgUserList(orgUser);
        return AjaxResult.success(list);
    }

    /**
     * 分页查询所有组织人员列表
     */
    @PostMapping("/orgUser/Pagelist")
    @CrossOrigin
    @ResponseBody
    public AjaxResult orgUserPagelist() {
        startPage();
        OrgUser orgUser = new OrgUser();
        List<OrgUser> list = orgUserService.selectOrgUserList(orgUser);
        return AjaxResult.success(getDataTable(list));
    }

    @PostMapping("/pullAllOrg")
    @CrossOrigin
    @ResponseBody
    public AjaxResult pullAllOrg() throws Exception {
        String result = HttpClientUtils.get("http://admin.rfiam.cnpc/ngiam-rst/v1/api/group/syncGroupPull?tenantId=5a2e25e222ba1f09d93ffa7a&pageNo=0&startTime=&endTime=");
        JSONObject orgObject = JSON.unmarshal(result,JSONObject.class);
        if (orgObject.get("code").equals("SUCCESS")){
            JSONObject data= orgObject.getObj("data");
            JSONObject.JSONArray jsonArray = data.getArr("groupInfos");
            if (null!=jsonArray && jsonArray.size()>0){
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject info = (JSONObject) jsonArray.get(i);
                    Org org = new Org();
                    org.setCode(info.getStr("code"));
                    org.setName(info.getStr("name"));
                    org.setParentCode(info.getStr("parentCode"));
                    org.setParentName(info.getStr("parentName"));
                    org.setDescription(info.getStr("description"));
                    org.setDeleted(info.getBool("deleted")==true?"1":"0");
                    org.setCreateDate(info.getStr("createDate"));
                    org.setLastUpdateDate(info.getStr("lastUpdateDate"));
                    org.setSerialNum(info.getStr("serialNum"));
                    org.setOldParentCode(info.getStr("oldParentCode"));
                    org.setOldParentName(info.getStr("oldParentName"));
                    orgService.insertOrg(org);
                }
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/pullAllOrgUser")
    @CrossOrigin
    @ResponseBody
    public AjaxResult pullAllOrgUser() throws Exception {
        String result = HttpClientUtils.get("http://admin.rfiam.cnpc/ngiam-rst/v1/api/user/userPull?tenantId=5a2e25e222ba1f09d93ffa7a&pageNo=0&startTime=&endTime=");
        JSONObject orgUserObject = JSON.unmarshal(result,JSONObject.class);
        if (orgUserObject.get("code").equals("SUCCESS")){
            JSONObject data= orgUserObject.getObj("data");
            JSONObject.JSONArray jsonArray = data.getArr("userInfos");
            if (null!=jsonArray && jsonArray.size()>0){
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject info = (JSONObject) jsonArray.get(i);
                    OrgUser orgUser = new OrgUser();
                    orgUser.setUserName(info.getStr("userName"));
                    orgUser.setDisplayName(info.getStr("displayName"));
                    orgUser.setEmail(info.getStr("email"));
                    orgUser.setMobile(info.getStr("mobile"));
                    orgUser.setEnabled(info.getBool("enabled")==true?"1":"0");
                    orgUser.setDeleted(info.getBool("deleted")==true?"1":"0");
                    JSONObject.JSONArray groups = info.getArr("groups");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int j = 0; j < groups.size(); j++) {
                        String group = (String) groups.get(j);
                        stringBuilder.append(group+",");
                    }
                    orgUser.setGroups(stringBuilder.substring(0,stringBuilder.length()-1));
                    orgUser.setCreateDate(info.getStr("createDate"));
                    orgUser.setLastUpdateDate(info.getStr("lastUpdateDate"));
                    orgUser.setIdentity(info.getStr("identity"));
                    orgUserService.insertOrgUser(orgUser);
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 通过组织机构查询人员是否存在
     */
    @PostMapping("/orgUser/checkUser")
    @CrossOrigin
    @ResponseBody
    public AjaxResult checkUser(HttpServletRequest request,Long orgId,String userName) {
        boolean isFind = false;
        Org org = orgService.selectOrgById(orgId);
        List<Org> list = orgService.selectOrgListByParentCode(org.getCode());
        if (list.size()==0){
            list.add(org);
        }
        String [] groups = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Org tempOrg = list.get(i);
            groups[i]=tempOrg.getCode();
        }
        List<OrgUser> resultList = orgUserService.selectOrgUserListByCode(groups);
        for (OrgUser orgUser:
             resultList) {
            if (orgUser.getEmail().split("@")[0].equals(userName)){
                isFind=true;
                break;
            }
        }
        return AjaxResult.success(isFind);
    }

    /**
     * 同步OA组织机构
     */
    @GetMapping("/oa/pullOrg")
    @CrossOrigin
    @ResponseBody
    public AjaxResult pullOrg(HttpServletRequest request) {
        List<OaOrg> list = oaOrgService.selectOaOrgList(new OaOrg());
        return AjaxResult.success(list);

    }
    /**
     * 同步OA组织机构人员
     */
    @GetMapping("/oa/pullUser")
    @CrossOrigin
    @ResponseBody
    public AjaxResult pullUser(HttpServletRequest request) {
        List<OaOrgUser> list = oaOrgUserService.selectOaOrgUserList(new OaOrgUser());
        return AjaxResult.success(list);

    }

    public static void main(String[] args) throws Exception {
//        String result = HttpClientUtils.get("http://admin.rfiam.cnpc/ngiam-rst/v1/api/user/userPull?tenantId=5a2e25e222ba1f09d93ffa7a&pageNo=0&startTime=&endTime=");
//        JSONObject orgUserObject = JSON.unmarshal(result,JSONObject.class);
//        System.out.print(result);
        new FrontController().pullAllOrg();
    }
}